package com.gitee.bailiny.processor;

import com.gitee.bailiny.connector.Request;
import com.gitee.bailiny.connector.Response;
import com.gitee.bailiny.util.http.HttpRequestLine;
import com.gitee.bailiny.util.http.SocketInputStream;

import javax.servlet.ServletException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author YangXu
 * @date 2022/3/26
 * @description:
 */
public class HttpProcessor {

    private HttpRequestLine requestLine = new HttpRequestLine();

    public void process(Socket socket) {
        SocketInputStream input;
        OutputStream output;
        try {
            input = new SocketInputStream(socket.getInputStream(), 2048);
            output = socket.getOutputStream();

            // 创建请求对象
            Request request = new Request(input);

            // 创建响应对象
            Response response = new Response(output);
            response.setRequest(request);

            response.setHeader("Server", "my servlet container");

            parseRequest(input, output);
            parseHeaders(input);

            /**
             * 判断是否是servlet，如果请求路径以/servlet/开头表示是一个servlet，否在是请求一个静态资源
             */
            if (request.getUri().startsWith("/servlet/")) {
                ServletProcessor processor = new ServletProcessor();
                processor.process(request, response);
            } else {
                StaticResourceProcessor processor = new StaticResourceProcessor();
                processor.process(request, response);
            }

            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseRequest(SocketInputStream input, OutputStream output) throws ServletException {
        input.readRequestLine(requestLine);
        String method = new String(requestLine.method, 0, requestLine.methodEnd);
        String uri = null;
        String protocol = new String(requestLine.protocol, 0, requestLine.protocolEnd);
        if (method.length() < 1) {
            throw new ServletException("没有请求方法");
        }
        if (protocol.length() < 1) {
            throw new ServletException("没有请求协议");
        }

    }

    private void parseHeaders(SocketInputStream input) {

    }
}
